<template>
	<view class="container">
		<view class="calculator">
			<!-- 参与人管理部分 -->
			<view class="section">
				<text class="section-title">参与人管理</text>
				<view class="input-group">
					<input 
						type="text" 
						v-model="newParticipantName" 
						placeholder="输入参与者姓名"
						@confirm="addParticipant"
						class="name-input"
					/>
					<button @tap="addParticipant" class="add-btn">添加参与者</button>
				</view>
				<view class="participants-list">
					<view v-for="(participant, index) in participants" :key="index" class="participant-item">
						<text>{{participant.name}}</text>
						<view class="advanced-payments">
							<view class="advanced-payment">
								<text>场地费垫付：</text>
								<input 
									type="digit" 
									:value="participant.advancedCourtFee"
									@input="(e) => updateAdvancedPayment(participant.name, 'court', e.detail.value)"
									class="fee-input"
								/>
							</view>
							<view class="advanced-payment">
								<text>球费垫付：</text>
								<input 
									type="digit" 
									:value="participant.advancedShuttlecockFee"
									@input="(e) => updateAdvancedPayment(participant.name, 'shuttlecock', e.detail.value)"
									class="fee-input"
								/>
							</view>
						</view>
						<button @tap="() => removeParticipant(participant.name)" class="delete-btn">删除</button>
					</view>
				</view>
			</view>

			<!-- 时间段配置部分 -->
			<view class="section">
				<text class="section-title">时间段配置</text>
				<view class="input-group">
					<text>总时长（小时）：</text>
					<input 
						type="digit" 
						v-model="hours" 
						@input="updateTimeSlots"
						class="hours-input"
					/>
				</view>
				<view class="time-slots">
					<view v-for="(slot, index) in timeSlots" :key="index" class="time-slot">
						<text class="time-range">{{formatTimeRange(index)}}</text>
						<view class="fee-config">
							<view class="input-group">
								<text>场地费：</text>
								<input 
									type="digit" 
									v-model="slot.courtFee"
									@input="calculateFees"
									class="fee-input"
								/>
							</view>
							<view class="input-group">
								<text>球费：</text>
								<input 
									type="digit" 
									v-model="slot.shuttlecockFee"
									@input="calculateFees"
									class="fee-input"
								/>
							</view>
							<view class="input-group">
								<text>其他：</text>
								<input 
									type="digit" 
									v-model="slot.otherFees"
									@input="calculateFees"
									class="fee-input"
								/>
							</view>
						</view>
						<view class="participants-row">
							<text>参与者：</text>
							<scroll-view scroll-x class="participants-scroll">
								<view class="participants-config">
									<view v-for="participant in participants" :key="participant.name" class="participant-checkbox">
										<checkbox 
											:checked="slot.participants.includes(participant.name)"
											@tap="() => toggleParticipant(index, participant.name)"
										/>
										<text>{{participant.name}}</text>
									</view>
								</view>
							</scroll-view>
						</view>
					</view>
				</view>
			</view>

			<button @tap="calculateFees" class="calculate-button">计算费用</button>

			<!-- 结果显示部分 -->
			<view class="result">
				<text class="section-title">费用明细</text>
				<view v-if="showWarning" class="warning-message">
					<text>⚠️ 警告：总费用与垫付总额不一致！</text>
					<text>总费用：{{totalFee}}元</text>
					<text>垫付总额：{{totalAdvanced}}元</text>
					<text>差额：{{diffAmount}}元</text>
				</view>
				<text>总费用：{{totalFee}}元</text>
				<view class="per-person-details">
					<view v-for="detail in personDetails" :key="detail.name" class="person-fee-detail">
						<text class="person-name">{{detail.name}}</text>
						<text>场地费：{{detail.courtFee}}元 (垫付: {{detail.advancedCourtFee}}元)</text>
						<text>球费：{{detail.shuttlecockFee}}元 (垫付: {{detail.advancedShuttlecockFee}}元)</text>
						<text>其他费用：{{detail.otherFees}}元</text>
						<text :class="['final-amount', detail.finalAmount >= 0 ? 'positive' : 'negative']">
							{{detail.finalAmount >= 0 ? '还需支付' : '需要返还'}}：{{Math.abs(detail.finalAmount)}}元
						</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			participants: [],
			timeSlots: [],
			newParticipantName: '',
			hours: 1,
			totalFee: 0,
			totalAdvanced: 0,
			diffAmount: 0,
			showWarning: false,
			personDetails: []
		}
	},

	methods: {
		addParticipant() {
			const name = this.newParticipantName.trim()
			if (name && !this.participants.find(p => p.name === name)) {
				this.participants.push({
					name,
					advancedCourtFee: 0,
					advancedShuttlecockFee: 0
				})
				this.newParticipantName = ''
				this.updateTimeSlots()
			}
		},

		removeParticipant(name) {
			this.participants = this.participants.filter(p => p.name !== name)
			this.updateTimeSlots()
		},

		updateAdvancedPayment(name, type, amount) {
			const participant = this.participants.find(p => p.name === name)
			if (participant) {
				if (type === 'court') {
					participant.advancedCourtFee = parseFloat(amount) || 0
				} else if (type === 'shuttlecock') {
					participant.advancedShuttlecockFee = parseFloat(amount) || 0
				}
				this.calculateFees()
			}
		},

		formatTimeRange(index) {
			const startHour = Math.floor(index / 2)
			const startMinute = (index % 2) * 30
			const endHour = Math.floor((index + 1) / 2)
			const endMinute = ((index + 1) % 2) * 30
			return `${startHour}:${startMinute === 0 ? '00' : startMinute} - ${endHour}:${endMinute === 0 ? '00' : endMinute}`
		},

		updateTimeSlots() {
			const totalSlots = Math.floor(this.hours * 2)
			this.timeSlots = Array(totalSlots).fill(null).map(() => ({
				participants: this.participants.map(p => p.name),
				courtFee: 0,
				shuttlecockFee: 0,
				otherFees: 0
			}))
			this.calculateFees()
		},

		toggleParticipant(slotIndex, participantName) {
			const slot = this.timeSlots[slotIndex]
			const index = slot.participants.indexOf(participantName)
			if (index === -1) {
				slot.participants.push(participantName)
			} else {
				slot.participants.splice(index, 1)
			}
			this.calculateFees()
		},

		calculateFees() {
			let totalCourtFee = 0
			let totalShuttlecockFee = 0
			let totalOtherFees = 0
			const personFees = {}
			let totalAdvancedCourtFee = 0
			let totalAdvancedShuttlecockFee = 0

			this.participants.forEach(participant => {
				personFees[participant.name] = {
					courtFee: 0,
					shuttlecockFee: 0,
					otherFees: 0
				}
				totalAdvancedCourtFee += participant.advancedCourtFee
				totalAdvancedShuttlecockFee += participant.advancedShuttlecockFee
			})

			this.timeSlots.forEach(slot => {
				totalCourtFee += parseFloat(slot.courtFee) || 0
				totalShuttlecockFee += parseFloat(slot.shuttlecockFee) || 0
				totalOtherFees += parseFloat(slot.otherFees) || 0

				if (slot.participants.length > 0) {
					const perPersonCourtFee = (parseFloat(slot.courtFee) || 0) / slot.participants.length
					const perPersonShuttlecockFee = (parseFloat(slot.shuttlecockFee) || 0) / slot.participants.length
					const perPersonOtherFee = (parseFloat(slot.otherFees) || 0) / slot.participants.length

					slot.participants.forEach(name => {
						personFees[name].courtFee += perPersonCourtFee
						personFees[name].shuttlecockFee += perPersonShuttlecockFee
						personFees[name].otherFees += perPersonOtherFee
					})
				}
			})

			this.totalFee = totalCourtFee + totalShuttlecockFee + totalOtherFees
			this.totalAdvanced = totalAdvancedCourtFee + totalAdvancedShuttlecockFee
			this.diffAmount = Math.abs(this.totalFee - this.totalAdvanced)
			this.showWarning = this.diffAmount > 0.01

			this.personDetails = Object.entries(personFees).map(([name, fees]) => {
				const participant = this.participants.find(p => p.name === name)
				const totalPersonFee = fees.courtFee + fees.shuttlecockFee + fees.otherFees
				const totalAdvancedByPerson = participant.advancedCourtFee + participant.advancedShuttlecockFee
				return {
					name,
					...fees,
					advancedCourtFee: participant.advancedCourtFee,
					advancedShuttlecockFee: participant.advancedShuttlecockFee,
					finalAmount: totalPersonFee - totalAdvancedByPerson
				}
			})
		}
	},

	mounted() {
		this.updateTimeSlots()
	}
}
</script>

<style>
.container {
	padding: 20px;
}

.section {
	background-color: #fff;
	padding: 15px;
	margin-bottom: 15px;
	border-radius: 8px;
	box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.section-title {
	font-size: 18px;
	margin-bottom: 10px;
	color: #333;
}

.input-group {
	display: flex;
	align-items: center;
	margin-bottom: 10px;
}

.name-input {
	flex: 1;
	height: 35px;
	padding: 0 10px;
	border: 1px solid #ddd;
	border-radius: 4px;
}

.fee-input {
	width: 80px;
	height: 35px;
	padding: 0 5px;
	border: 1px solid #ddd;
	border-radius: 4px;
}

.participant-item {
	display: flex;
	align-items: center;
	padding: 10px;
	margin: 5px 0;
	background-color: #f8f9fa;
	border-radius: 4px;
}

.advanced-payments {
	display: flex;
	gap: 10px;
	margin: 0 10px;